package com.itheima.qingcheng.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.util.StringUtil;
import com.itheima.qingcheng.exception.CurrentException;
import com.itheima.qingcheng.mapper.LoginMapper;
import com.itheima.qingcheng.pojo.Dto.LoginDto;
import com.itheima.qingcheng.pojo.User;
import com.itheima.qingcheng.pojo.Vo.LoginVo;
import com.itheima.qingcheng.service.UserService;
import com.itheima.qingcheng.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author zhangzhen
 * @version 1.0
 * @date 2025/1/21 11:10
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired private LoginMapper loginMapper;
    @Override
    public LoginVo login(LoginDto loginDto) {
        if(ObjUtil.isEmpty(loginDto)|| StringUtil.isEmpty(loginDto.getUsername())||
        StringUtil.isEmpty(loginDto.getPassword())){
            throw new CurrentException("用户名或者密码不为空");

        }

        User user = loginMapper.selectByUsername(loginDto.getUsername());
        if(ObjUtil.isEmpty(user)){
        throw  new CurrentException("用户名不存在");
        }
        if (!StrUtil.equals(loginDto.getPassword(),user.getPassword())){
            throw new CurrentException("用户名或者密码错误");
        }
        LoginVo loginVo= BeanUtil.toBean(user, LoginVo.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",loginVo.getId());
        map.put("username",loginDto.getUsername());
        String token = JwtUtils.generateJwt(map);
        loginVo.setToken(token);
        return  loginVo;
    }


}